package com.lxyk.yygh.user.aop;

import com.baomidou.mybatisplus.extension.api.R;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Aspect
@Component
@Slf4j
public class RequestLimitAspect {
//    不单只存次数，还需要存储第一次访问的时间
    private Map<String, RequestInfo> requestCountMap=new ConcurrentHashMap<>();
    private static final int  MAX_REQUEST_COUNT=5;//允许的最大连续请求次数，1h内
    private static final long INTERVAL=1800000;

    @Before("@annotation(RequestLimit)")
    public void before(JoinPoint joinPoint){
        String clientIP=getClientIP();
        log.info("访问ip==================>{}",clientIP);
        long curTime = System.currentTimeMillis();
        //根据ip获取
        RequestInfo requestInfo = requestCountMap.get(clientIP);
//        存在且不超过时间
        if(requestInfo!=null&&requestInfo.getCount()<MAX_REQUEST_COUNT){
            if(curTime-requestInfo.getTime()<INTERVAL){
                //更新
                int count = requestInfo.getCount();
                requestInfo.setCount(count+1);
                requestCountMap.getOrDefault(clientIP,requestInfo);
            }else{
                throw new RuntimeException("限制登陆，访问失败");
            }
        }else{
            requestCountMap.getOrDefault(clientIP,new RequestInfo(System.currentTimeMillis(),1));
        }

    }



    public String getClientIP() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }
}
